package com.manzuo.framework.web.subdomain;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.manzuo.framework.web.RequestAttributeConstants;

@Component("subdomainFilter")
public class SubDomainRewriteFilter extends OncePerRequestFilter implements Filter {
		
	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		String serverName = request.getServerName();
		String[] splited = serverName.split("\\.");
		if(ArrayUtils.isNotEmpty(splited) && splited.length >= 3) {
			String subDomain = splited[0];
			if(StringUtils.isNotBlank(subDomain)) {
				request.setAttribute(RequestAttributeConstants.REQUEST_ATTRIBUTE_SUB_DOMAIN, subDomain);
			} else {
				request.setAttribute(RequestAttributeConstants.REQUEST_ATTRIBUTE_SUB_DOMAIN, "_null_sub_domin_");
			}
		} else {
			request.setAttribute(RequestAttributeConstants.REQUEST_ATTRIBUTE_SUB_DOMAIN, "_null_sub_domin_");
		}
		chain.doFilter(request, response);
	}

}
